package com.study.base.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * Description:[java中四种引用类型（对象的强、软、弱和虚引用） \- CSDN博客](http://blog.csdn.net/u011936381/article/details/11709245)
 * User: tan
 * DateTime: 2018/2/9 16:09
 */
public class ReferenceTest {
    public static void main(String[] args) throws InterruptedException {

        Object object = new Object();//强引用

        SoftReference<Object> softReference = new SoftReference<>(object);

        WeakReference<Object> weakReference = new WeakReference<>(object);
        System.gc();

        Thread.sleep(10);
        System.out.println("soft " + softReference.get());
        System.out.println("weak " + weakReference.get());

        object = null;//去掉强引用
        //这时候 当即将内存溢出异常时，soft引用被清理掉 softReference.get()得到null
        //遇到任何gc，weakreference 会被清理掉  weakReference.get()得到null
        System.gc();
        System.out.println("soft " + softReference.get());
        System.out.println("weak " + weakReference.get());

        // 使用ReferenceQueue清除失去了软引用对象的SoftReference
        //当软可及对象被回收之后，虽然这个SoftReference对象的get()方法返回null,但这个SoftReference对象已经不再具有存在的价值，需要一个适当的清除机制，避免大量SoftReference对象带来的内存泄漏。
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        SoftReference<Object> softReference1 = new SoftReference<>(object, referenceQueue);



    }
}
